<?php

namespace app\web\controller;

use think\Controller;
use think\Db;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use OSS\OssClient;
use OSS\Core\OssException;
use think\Exception;
use think\facade\Log;

class Alivideo extends Controller {

    public $sysset;

    public function __construct(\think\App $app = null) {
        parent::__construct($app);

        $this->sysset = get_sysset();
    }

    public function index() {

        $_GPC = input();
        ignore_user_abort(true);
        set_time_limit(0);
        $this->sysset = get_sysset();
        $sale = pdo_get('sale', array('id' => $_GPC['sale_id']));
        $video = json_decode($sale['video'], true);
        if (isset($video['RequestIds'])) {
            asyn_http_get($this->request->domain(true) . '/web/alivideo/getjobres?idx=0&sale_id=' . $sale['id'] . '&num=0');
            exit('执行成功，视频正在生成，请等待10分钟左右，若视频还是不能生成，请联系客服。');
        }
        $accessKeyId = $this->sysset['basic']['ali_keyid'];
        $accessKeySecret = $this->sysset['basic']['ali_keysecret'];
        $endpoint = "http://oss-cn-shanghai.aliyuncs.com";
        $bucket = $this->sysset['basic']['ali_bucketname'];
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $filelist = array();
        foreach ($video['alivideo']['media'] as $key => $value) {
            $object = substr($value['path'], strrpos($value['path'], '/') + 1);
            $filePath = $_SERVER['DOCUMENT_ROOT']  . $value['path'];
            switch (substr($object, strrpos($object, '.') + 1)) {
                case 'mp4':
                    $fileType = 'video';
                    break;
                case 'mp3':
                    $fileType = 'audio';
                    break;
                default:
                    $fileType = 'image';
                    break;
            }
            $result = $ossClient->uploadFile($bucket, $object, $filePath);
            Log::info($result);
            if (isset($result['oss-request-url'])) {
                $filelist[] = array('FileName' => $object, 'FileUrl' => $result['oss-request-url'], 'Type' => $fileType);
            }
        }
        AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)->regionId('cn-shanghai')->asDefaultClient();
        $RequestIds = array();
        $num = 0;
        while ($num < $video['alivideo']['num']) {
            try {
                shuffle($filelist);
                if (isset($options)) {
                    unset($options);
                }
                $options = array('RegionId' => "cn-shanghai",
                    'Width' => $video['alivideo']['width'] ? $video['alivideo']['width'] : "720",
                    'Height' => $video['alivideo']['height'] ? $video['alivideo']['height'] : "1280",
                    'Duration' => mt_rand($video['alivideo']['min'] ? $video['alivideo']['min'] : 20, $video['alivideo']['max'] ? $video['alivideo']['max'] : 30),
                    'DurationAdaption' => "false",
                    'Mute' => "false",
                    'Scene' => 'general',
                    'SmartEffect'=>"true");
                foreach ($filelist as $key => $value) {
                    $options['FileList.' . ($key + 1) . '.FileName'] = $value['FileName'];
                    $options['FileList.' . ($key + 1) . '.FileUrl'] = $value['FileUrl'];
                    $options['FileList.' . ($key + 1) . '.Type'] = $value['Type'];
                }
                Log::info('剪辑开始：');
                Log::info('剪辑参数：');
                Log::info($options);
                $result = AlibabaCloud::rpc()->product('videoenhan')
                    ->version('2020-03-20')
                    ->action('GenerateVideo')
                    ->method('POST')
                    ->host('videoenhan.cn-shanghai.aliyuncs.com')
                    ->options(array('query' => $options))
                    ->request();
                $res = $result->toArray();
                Log::info('剪辑结果：');
                Log::info($res);
                if (isset($res['RequestId'])) {
                    $RequestIds[] = $res['RequestId'];
                }
            }catch (\Exception $exception){
                Log::info('错误信息：');
                Log::info($exception->getMessage());
            }
            $num++;
            sleep(1);
        }
        $video['RequestIds'] = $RequestIds;
        $sale['video'] = json_encode($video);
        try {
            pdo_update('sale', $sale, array('id' => $sale['id']));
        }catch (Exception $exception){
            Log::info("修改出错：");
            Log::info($exception->getMessage());
        }
        asyn_http_get($this->request->domain(true) . '/web/alivideo/getjobres?idx=0&sale_id=' . $sale['id'] . '&num=0');
        exit('执行成功，视频正在生成，请等待10分钟左右，若视频还是不能生成，请联系客服。');
    }

    public function getjobres() {
        $_GPC = input();
        ignore_user_abort(true);
        set_time_limit(0);
        try {
            $sale = pdo_get('sale', array('id' => $_GPC['sale_id']));
            $video = json_decode($sale['video'], true);
            $accessKeyId = $this->sysset['basic']['ali_keyid'];
            $accessKeySecret = $this->sysset['basic']['ali_keysecret'];
            AlibabaCloud::accessKeyClient($accessKeyId, $accessKeySecret)
                ->regionId('cn-shanghai')
                ->asDefaultClient();
            $num = intval($_GPC['num']);
            $i = intval($_GPC['idx']);
            if ($num < count($video['RequestIds'])) {
                if ($i >= 30) {
                    $num++;
                    $i = 0;
                }
                $result = AlibabaCloud::rpc()->product('videoenhan')
                    ->version('2020-03-20')
                    ->action('GetAsyncJobResult')
                    ->method('POST')
                    ->host('videoenhan.cn-shanghai.aliyuncs.com')
                    ->options(array('query' => array('RegionId' => "cn-shanghai", 'JobId' => $video['RequestIds'][$num])))
                    ->request()
                    ->toArray();

                if ($result['Data']['Status'] == 'PROCESS_SUCCESS') {
                    $num++;
                    $i = 0;
                    $data = json_decode($result['Data']['Result'], true);

                    $videodata = file_get_contents($data['VideoUrl']);
                    self::mkdirs('upload/' . date("Ym"));
                    $path = 'upload/' . date("Ym") . '/'. md5($data['VideoUrl']) . '.mp4';
                    file_put_contents($path, $videodata);

                    $video['list'][] = array('title' => $video['alivideo']['title'], 'path' => $path);
                    $video['alivideo']['num']--;
                    if ($video['alivideo']['num'] == 0) {
                        unset($video['alivideo']);
                        unset($video['RequestIds']);
                    }
                    $sale['video'] = json_encode($video);
                    pdo_update('sale', $sale, array('id' => $sale['id']));
                    sleep(3);
                } else {
                    sleep(15);
                    $i++;
                }
            }
        }catch (\Exception $exception){
            Log::info("下载错误：");
            Log::info($exception->getMessage());
        }
        asyn_http_get($this->request->domain(true) . '/web/alivideo/getjobres?idx=' . $i . '&sale_id=' . $sale['id'] . '&num=' . $num);
        exit;
    }
    
    public function mkdirs( $dir ,  $mode  = 0777)
    {
         if  ( is_dir( $dir ) || @mkdir( $dir ,  $mode ))  return  TRUE;
         if  (!mkdirs(dirname( $dir ),  $mode ))  return  FALSE;
         return  @mkdir( $dir ,  $mode );
    }

}
